Barcelona coach Xavi Hernandez said he will leave his post at the end of the season after his struggling team were beaten 5-3 by Villarreal on Saturday in La Liga.

"On June 30 I will leave the club, it's a decision I have taken with the president, with the staff," Xavi told reporters.

Champions Barcelona, third in the top flight, are 10 points behind leaders Real Madrid with their title defence virtually over.

After elimination in the Copa del Rey by Athletic Bilbao this week and a thrashing by Madrid in the Spanish Super Cup final earlier in January, Xavi said he made the decision for the good of the club.

"I've thought about the club ... and above all the players," said Xavi.

"I have the feeling that I am doing the right thing, that I am acting with common sense.

"I think the club needs a change of dynamics, the dynamic is very negative."

Xavi, who took over in November 2021, led Barcelona to the Spanish Super Cup and league title last season, with the team built around a strong defence.

However this year they are fragile at the back and Saturday saw Barcelona let in five goals in La Liga at home for the first time since 1963.

Xavi said even if Barcelona won the Champions League he would not change his mind and stay.

The coach, 44, said he still thought his team could win trophies this season.

"I am more optimistic than ever with this change of dynamic ... we'll go for La Liga, it's very difficult but we will fight," he added.

"I have not spoken to the players about it, I saw how down they were today and I will talk to them tomorrow, and that's one of the reasons for it."