Reikenz
2 months ago
168
1
Laravel

Ajax view

Posted 2 months ago by Reikenz

I would like that as soon as an ajax request is sent where there is view ('view') instead of returning the raw view its returns a JSON

Like that:

	/**
	 * @param \Illuminate\Contracts\View\View $view
	 * @return \Illuminate\Http\JsonResponse
	 */
    protected function ajaxResponse (View $view)
    {
	    return response()->json([
		    'id' => $view->getData()['page'],
		    'title' => $view->getData()['title'],
		    'content' => $view->renderSections()['content'],
		    'replacepage' => null,
	    ]);
    }

But I absolutely don't know how to do it I don't want to repeat myself in each controller

I have tried to replace View with mine but it does not work as I would like everything to work but I cannot recover the section of my page

<?php

namespace App\Extensions\View;

use Illuminate\View\View;

class AjaxView extends View
{
	/**
	 * Get the contents of the view instance.
	 *
	 * @return string
	 * @throws \Throwable
	 */
	protected function renderContents()
	{
		if(request()->ajax()) {
			echo $this->getResponse($this->getData());
			exit;
		}

		return parent::renderContents();
	}

	/**
	 * @param array $data
	 * @return false|string
	 */
	public function getResponse (array $data = [])
	{
		return json_encode([
			'id' => $data['page'],
			'title' => (!empty($data['title']) ? $data['title'] . ' - ' . config('app.name') : null),
			'content' => $this->renderSections()['content'],
			'replacepage' => null
		]);
	}

}

This returns that : https://i.imgur.com/ZOi7j7H.png

Please sign in or create an account to participate in this conversation.